package com.css.security.browser.controller;

import com.css.common.core.utils.R;
import com.css.common.security.constant.SecurityConstants;
import com.css.common.security.properties.SecurityProperties;
import com.css.common.security.support.SocialUserInfo;
import com.css.security.core.social.SocialController;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * BrowserSecurityController
 * 浏览器环境下与安全相关的服务
 *
 * @author hanyx
 * @date 2019/04/11
 */
@Slf4j
@Api(tags = {"Security-Browser"})
@RestController
public class BrowserSecurityController extends SocialController {

    private RequestCache requestCache = new HttpSessionRequestCache();
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private ProviderSignInUtils providerSignInUtils;

    private ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 用户第一次社交登录时，会引导用户进行用户注册或绑定
     * 此服务用于在注册或绑定页面获取社交网站用户信息
     *
     * @param request
     * @return
     */
    @GetMapping(SecurityConstants.DEFAULT_SOCIAL_USER_INFO_URL)
    public SocialUserInfo getSocialUserInfo(HttpServletRequest request) {
        Connection<?> connection = providerSignInUtils.getConnectionFromSession(new ServletWebRequest(request));
        return buildSocialUserInfo(connection);
    }

    /**
     * 当需要身份认证时，跳转到这里
     * html请求跳转默认登录页面, 否则返回json
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public void requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        if (savedRequest != null) {
            log.info("引发跳转的请求是:" + savedRequest.getRedirectUrl());
            if (StringUtils.endsWithIgnoreCase(savedRequest.getRedirectUrl(), SecurityConstants.HTML_SUFFIX)) {
                redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getSignInPage());
            }
        }
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(SecurityConstants.APPLICATION_JSON_CONTENT_TYPE);
//        response.getWriter().write(objectMapper.writeValueAsString(R.buildError("访问的服务需要身份认证，请引导用户到登录页")));
        response.getWriter().write(objectMapper.writeValueAsString(R.buildError("登录超时，请重新登录",30002)));
    }

}
